package com.jron.cqiu.util;

import com.jron.cqiu.Constants;
import com.jron.cqiu.kernel.implement.ReadProperties;

import java.util.*;
import java.io.IOException;
import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.StringUtils;

/**
 * Created by Intellij IDEA.
 *
 * @Author: Yejw
 * @Date: 2008-6-16
 * @Time: 14:03:32
 */
public class ConfigurationUtil {

    private static Log log = LogFactory.getLog(ConfigurationUtil.class);

    private static Properties props = null;

    /**
     * 获取属性值
     *
     * @param key
     * @return
     */
    public static String value(String key) {
        String val = null;
        String userProp = FilePath.getParentAbsolutePath(Constants.USER_BUNDLE_KEY + Constants.PROPERTY_FILE_SUFIX);
        File userPropFile = new File(userProp);
        if (userPropFile.exists()) {
            if (props == null) {
                props = new Properties();
                try {
                    props.load(FileUtils.openInputStream(userPropFile));
                } catch (IOException e) {
                    log.debug(e.getMessage());
                }
            }
            if (props.containsKey(key)) {
                val = props.getProperty(key);
                if (StringUtils.isNotBlank(val)) return val;
            }
        }
        return ReadProperties.instance(Constants.BUNDLE_KEY).getProperties().get(key);
    }

    /**
     * Method to convert a ResourceBundle to a Map object.
     *
     * @param rb a given resource bundle
     * @return Map a populated map
     */
    public static Map<String, String> convertBundleToMap(ResourceBundle rb) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<String> keys = rb.getKeys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            map.put(key, rb.getString(key));
        }
        return map;
    }


    /**
     * Method to convert a ResourceBundle to a Properties object.
     *
     * @param rb a given resource bundle
     * @return Properties a populated properties object
     */
    public static Properties convertBundleToProperties(ResourceBundle rb) {
        Properties props = new Properties();
        for (Enumeration<String> keys = rb.getKeys(); keys.hasMoreElements();) {
            String key = keys.nextElement();
            props.put(key, rb.getString(key));
        }
        return props;
    }
}
